<template>
  <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图 -->
      <el-card>
        <!-- 栅格布局 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input clearable @clear='getUserList' v-model="queryData.query" placeholder="请输入内容" class="input-with-select">
            <el-button @click='getUserList' slot="append" icon="el-icon-search"></el-button>
          </el-input>
          </el-col>
          <el-col :span="4">
            <el-button @click='addDialogVisible = true' type="primary">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 用户列表区 -->
        <el-table :data="users" stripe border>
          <el-table-column type="index" width="50" label= #></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <!-- 关于组件暴露的数据 el-table-column组件已经写好了 table-column 内部 <slot :row='item></slot>' -->
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change='switchChange(scope.row)'></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" width="200">
            <!-- 包裹元素 -->
            <template slot-scope="scope">
              <el-button @click='showEditDialog(scope.row)' type="primary" icon="el-icon-edit" size="mini"></el-button>
              <el-button @click='removeUser(scope.row.id)' type="danger" icon="el-icon-delete" size="mini"></el-button>
              <el-tooltip :enterable='false' class="item" effect="dark" content="分配角色" placement="top">
               <el-button @click='showSetRole(scope.row)' type="warning" icon="el-icon-setting" size="mini"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页区 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryData.pagenum"
          :page-sizes="[2, 4, 10, 20]"
          :page-size="queryData.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
      <!-- 添加用户对话框 -->
      <el-dialog
      @close='dialogClose'
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%">
        <!-- 内容主体区 -->
        <el-form :rules='addUserFormRules' :model="addUserForm" ref="addUserFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAddForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 点击编辑对话框 -->
      <el-dialog
      @close='editDialogClose'
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%">
        <el-form :rules='editserRules' :model="editUserForm" ref="editUserFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        @close='closeSetDialog'
        title="分配角色"
        :visible.sync="setRolesDialogVisible"
        width="50%">
        <p>当前的用户： {{currentUser.username}} </p>
        <p>当前的角色： {{currentUser.role_name}} </p>
        <div>分配新的角色：
          <el-select v-model="selectValue" placeholder="请选择角色">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSetRoles">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'users',
  data () {
    // 邮箱自定义校验规则
    const checkEmail = (rule, value, callback) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('邮箱格式不合法'))
    }
    // 手机自定义校验规则
    const checkMobile = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('手机号格式错误'))
    }
    return {
      // 传递给后台的数据
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 接收列表数据
      users: [],
      // 接收总条数
      total: 0,
      // 控制添加用户对话框
      addDialogVisible: false,
      // 添加表单对象
      addUserForm: {
        username: 'qwer',
        password: '9876543',
        email: '77@qq.com',
        mobile: '13298400372'
      },
      // 添加用户表单校验规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制编辑对话框
      editDialogVisible: false,
      // 编辑用户表单对象
      editUserForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 编辑用户表校验规则
      editserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框限时和隐藏
      setRolesDialogVisible: false,
      // 当前用户信息
      currentUser: {},
      // 分配角色
      roles: [],
      selectValue: ''
    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    // 获取用户列表数据
    async getUserList () {
      const { data: res } = await this.$axios.get('users', {
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败！')
      this.users = res.data.users
      this.total = res.data.total
    },
    // 选择每页的条数
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getUserList()
    },
    // 更改页码值
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUserList()
    },
    // 监听开关发生变化
    async switchChange (item) {
      const { data: res } = await this.$axios.put(`users/${item.id}/state/${item.mg_state}`)
      if (res.meta.status !== 200) {
        item.mg_state = !item.mg_state
        this.$message.error('更改失败！')
        return
      }
      this.$message.success('更改成功！')
    },
    // 对话框关闭
    dialogClose () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 提交用户
    submitAddForm () {
      this.$refs.addUserFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('/users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('创建失败!')
        this.$message.success('创建成功!')
        // 关闭对话框
        this.addDialogVisible = false
        // 重新获取列表数据
        this.getUserList()
      })
    },
    // 点击编辑对话框
    showEditDialog (item) {
      this.editUserForm = item
      this.editDialogVisible = true
    },
    // 监听编辑对话框
    editDialogClose () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 提交编辑用户
    submitEditUser () {
      this.$refs.editUserFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put('users/' + this.editUserForm.id, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('提交失败!')
        this.$message.success('提交成功!')
        // 关闭对话框
        this.editDialogVisible = false
        // 重新获取列表数据
        this.getUserList()
      })
    },
    // 点击删除用户
    removeUser (id) {
      this.$confirm('此操作将永久删除该用户', '是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点击了确认
        const { data: res } = await this.$axios.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        this.$message.success('删除成功!')
        this.getUserList()
      }).catch(() => {
        // 点击了取消
        this.$message.info('已取消删除')
      })
    },
    // 点击分配角色
    async showSetRole (row) {
      this.setRolesDialogVisible = true
      this.currentUser = row
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      this.roles = res.data
    },
    // 点击确定分配角色
    async submitSetRoles () {
      if (this.selectValue === '') return this.$message.error('请选择分配角色!')
      const { data: res } = await this.$axios.put('users/' + this.currentUser.id + '/role', {
        rid: this.selectValue
      })
      if (res.meta.status !== 200) return this.$message.error('设置失败!')
      this.setRolesDialogVisible = false
      this.getUserList()
      this.$message.success('设置成功!')
    },
    // 监听对话框
    closeSetDialog () {
      this.selectValue = ''
    }
  }
}
</script>

<style scoped lang='less'>

</style>
